package cn.ywang.activemq;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

/**
 * 发布订阅消费者1
 *
 * @author: BeatificWang
 * @date: 2018/12/22 17:04
 */
public class PubSubPersistentConsumer {
	public static void main(String[] args) {
		ConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:61616");
		Connection connection = null;
		try {
			String clientID = "wang";
			// 创建连接
			connection = factory.createConnection();
			connection.setClientID(clientID);
			connection.start();
			Session session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
			// 主题
			Topic topic = session.createTopic("myTopic");
			// 持久化订阅，订阅者未激活时消息生产者发送消息，订阅者激活后可以收到消息
			MessageConsumer consumer = session.createDurableSubscriber(topic, clientID);
			// 消息
			TextMessage message = (TextMessage) consumer.receive();
			System.out.println(message.getText());
			// 消息签收
			session.commit();
			// 消息重新处理
			// <p> session.rollback() <p>
			session.close();
		} catch (JMSException e) {
			e.printStackTrace();
		} finally {
			if (connection != null) {
				try {
					connection.close();
				} catch (JMSException e) {
					e.printStackTrace();
				}
			}
		}
	}

}
